#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''

import datetime
import importlib
import threading
import time
from com.zxy.adminlog.UsAdmin_Log import UsAdmin_Log
from com.plugins.A01_6GG8T3.A01_6GG8T3_Time import A01_6GG8T3_Time
from com.zxy.autoUpdate.GetVersion import GetVersion
from com.zxy.common import Com_Para
from com.zxy.common.Com_Fun import Com_Fun
from com.zxy.business.Ope_DB_Cent import Ope_DB_Cent
from com.zxy.z_debug import z_debug
class TimeTask(z_debug):
    def __init__(self, rundatetime, delay, Interval, sleeps, sname):
        self.rundatetime = rundatetime
        self.delay = delay
        self.Interval = Interval
        self.sleeps = sleeps
        self.sname = sname
    def stimedo(self):
        Com_Para.bTimeFlag = True
        self.runTask()
        Com_Para.bTimeFlag = False
    def run(self):
        t = threading.Thread(target=self.show, name=self.sname)
        t.start()
    def RunReflectInClass(self):
        if Com_Para.TimeREFLECT_IN_CLASS != "":
            try:
                objC = importlib.import_module(Com_Para.TimeREFLECT_IN_CLASS)  #对模块进行导入                
                objName = Com_Para.TimeREFLECT_IN_CLASS.split(".")
                objN = getattr(objC,objName[len(objName) - 1])
                if hasattr(objN,"strContinue"):
                    fun_us = getattr(objN,"init_start")
                    fun_us(objN)
            except Exception as e:
                if str(type(self)) == "<class 'type'>":
                    self.debug_in(self,repr(e))#打印异常信息
                else:
                    self.debug_in(repr(e))#打印异常信息
            finally:
                pass
    def runTask(self):      
        try: 
            self.RunReflectInClass()
            if Com_Para.iTimeCount2 % (90 / self.Interval) == 0:
                self.SetSession()
                self.SendServerInfo()
                self.SendClientInfo()
            Com_Para.iTimeCount2 = Com_Para.iTimeCount2 + 1
            if Com_Para.iTimeCount2 >= (1800 / self.Interval) :   #300 / self.Interval             
                if Com_Para.urlPath != "":
                    gv = GetVersion()
                    gv.CheckVersion()           
                Com_Para.iTimeCount2 = 0
        except Exception as e:
            if str(type(self)) == "<class 'type'>":
                self.debug_in(self,repr(e))#打印异常信息
            else:
                self.debug_in(repr(e))#打印异常信息
        finally:
            pass
    def SendServerInfo(self):
        for temClientSocket in list(Com_Para.dClientThreadList.keys()):
            try:
                Com_Fun.SendSocket("S* "+Com_Fun.GetTimeDef(),Com_Para.dClientThreadList[temClientSocket])
            except Exception as e:
                del Com_Para.dClientThreadList[temClientSocket]
                temLog = ""
                if str(type(self)) == "<class 'type'>":
                    temLog = self.debug_info(self)+repr(e)
                else:
                    temLog = self.debug_info()+repr(e)
                uL = UsAdmin_Log(Com_Para.ApplicationPath, temLog)
                uL.WriteLog()
    def SendClientInfo(self):
        for temServerSocket in list(Com_Para.dServThreadList.keys()):
            try:
                Com_Fun.SendSocket("C* "+Com_Fun.GetTimeDef(),Com_Para.dServThreadList[temServerSocket])
            except Exception as e:
                del Com_Para.dServThreadList[temServerSocket]
                temLog = ""
                if str(type(self)) == "<class 'type'>":
                    temLog = self.debug_info(self)+repr(e)
                else:
                    temLog = self.debug_info()+repr(e)
                uL = UsAdmin_Log(Com_Para.ApplicationPath, temLog)
                uL.WriteLog()
    def SetSession(self):
        if Com_Para.iTimeCount2 % 2 == 0 :
            odc = Ope_DB_Cent()
            odc.SetInterSession()
        for key in list(Com_Para.htSession.keys()):
            Com_Fun.HadSession(key,"-1")
    def show(self):
        starttime = datetime.datetime.now()
        if self.rundatetime != 0 :
            while True:
                starttime = datetime.datetime.now()
                if (starttime - self.rundatetime).seconds > 0 and not Com_Para.bTimeFlag :
                    self.stimedo()
                    break
                else:
                    time.sleep(self.sleeps)
        if self.delay != 0:
            endtime = datetime.datetime.now() + datetime.timedelta(seconds=self.delay)
            while True:
                starttime = datetime.datetime.now()
                if starttime >= endtime and not Com_Para.bTimeFlag:
                    self.stimedo()
                    break
                else:
                    time.sleep(self.sleeps)
        if self.Interval != 0:
            endtime = starttime + datetime.timedelta(seconds=self.Interval)
            while True:
                starttime = datetime.datetime.now()
                if starttime >= endtime and not Com_Para.bTimeFlag:
                    if starttime >= endtime + datetime.timedelta(seconds=self.Interval):
                        endtime = endtime + 2*datetime.timedelta(seconds=self.Interval)
                    else:
                        endtime = endtime + datetime.timedelta(seconds=self.Interval)
                    self.stimedo()
                elif (endtime - starttime).seconds > 10 * self.Interval:
                    endtime = datetime.datetime.now() + datetime.timedelta(seconds=self.Interval)
                else:
                    time.sleep(self.sleeps)